package com.dolphin;

import cn.hutool.core.io.FileUtil;
import com.dolphin.commons.Constants;
import com.dolphin.config.UniqueNameGenerator;
import com.dtflys.forest.springboot.annotation.ForestScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableAsync;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

@SpringBootApplication
@ComponentScan(nameGenerator = UniqueNameGenerator.class)
@EnableAsync
@EnableAspectJAutoProxy
@ForestScan(basePackages = "com.dolphin.forest")
public class Application {
    private final static Logger LOGGER = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) throws UnknownHostException {
        boolean isDocker = Arrays.asList(args).contains(Constants.IS_DOCKER);
        if (isDocker) {
            updateDockerResources();
        }
        ConfigurableApplicationContext application = SpringApplication.run(Application.class, args);
        Environment env = application.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        String property = env.getProperty("server.servlet.context-path");
        String path = property == null ? "" : property;

        LOGGER.info(
                "\n" +
                        "----------------------------------------------------------\n\t" +
                        "Application is running! Access URLs:\n\t" +
                        "Local: \t\thttp://localhost:" + port + path + "\n\t" +
                        "External: \thttp://" + ip + ":" + port + path + "\n" +
                        "----------------------------------------------------------\n");
    }

    /**
     * @description 更新docker资源文件
     * @author dolphin
     */
    private static void updateDockerResources() {
        File appFile = new File("/app");
        if (!appFile.exists() || !appFile.isDirectory()) {
            return;
        }
        File[] files = appFile.listFiles();
        if (files == null || files.length <= 0) {
            return;
        }
        File resourcesFile = new File("/");
        for (File file : files) {
            if (!file.getName().equals("dolphin-web.jar")) {
                FileUtil.copy(file.getAbsolutePath(), resourcesFile.getAbsolutePath(), true);
            }
        }
        FileUtil.del(appFile.getAbsolutePath());
    }
}
